import os,sys
import cv2
from math import ceil

try:
    input_file = sys.argv[1]
except:
    input_file = 'test.jpg'
try:
    input_file = sys.argv[2]
except:
    output_file = 'crop.jpg'


def crop_image(filepath,BoxInfo):
    def value(info):
        return int(info.split(':')[-1])

    cols,rows = [],[]
    for info in BoxInfo:
        if info.split(':')[0] == 'col':
            cols.append(info)
        else:
            rows.append(info)

    cols,rows = [value(col) for col in cols],[value(row) for row in rows]
    top,left,bottom,right = min(cols),min(rows),max(cols),max(rows)

    image = cv2.imread(filepath)

    height,width,_ = image.shape
    deci_width,deci_height = ceil(width/10),ceil(height/10)

    top -= ceil(deci_height/2)
    bottom += ceil(deci_height/2)
    left -= ceil(deci_width/2)
    right += ceil(deci_width/2)

    cropped_image = image[left:right,top:bottom]

    return cropped_image



if __name__ == '__main__':
    BOX = ['col:718','row:300','col:908','row:498']
    BOX = ['row:300','col:718','row:498','col:908']
    BOX = ['row:498','col:718','row:300','col:908']
    BOX = ['col:908','row:498','row:300','col:718']
    BOX = ['row:498','row:300','col:718','col:908']
    cropped_image = crop_image(input_file,BOX)
    cv2.imwrite(output_file,cropped_image)
